package cn.mysource.org.service.impl;

import cn.mysource.basic.service.impl.BaseServiceImpl;
import cn.mysource.org.domain.Department;
import cn.mysource.org.mapper.DepartmentMapper;
import cn.mysource.org.service.IDepartmentService;
import cn.mysource.basic.util.PageList;
import cn.mysource.org.query.DepartmentQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper mapper;

//    @Override
//    public Department findById(Long id) {
//        return mapper.findById(id);
//    }
//
//    @Override
//    public List<Department> findAll() {
//        return mapper.findAll();
//    }
//
//    @Override
//    public void add(Department department) {
//        mapper.add(department);
//    }
//
//    @Override
//    public void update(Department department) {
//        mapper.update(department);
//    }
//
//    @Override
//    public void delete(Long id) {
//        mapper.delete(id);
//    }

//    @Override
//    public PageList<Department> queryByPage(DepartmentQuery query) {
//        // 查询 条数
//        Integer totals = mapper.queryByCount(query);
//        if (null == totals || 0 == totals){
//            return new PageList<Department>(0,new ArrayList<>());
//        }
//
//        // 查询数据把
//        List<Department> rows = mapper.queryByPage(query);
//        return new PageList<>(totals,rows);
//    }
//
//    @Override
//    public void batchDelete(List<Long> ids) {
//        mapper.batchDelete(ids);
//    }
    @Override
    public List<Department> tree() {
        List<Department> result = new ArrayList<>();
        // 查询出所有的数据
        List<Department> allDepartments = mapper.findAll();
        // 将 全部的部门数据 转成map key  value
        Map<Long, Department> deptMap = allDepartments.stream().collect(Collectors.toMap(Department::getId, dept -> dept));
//        Map<Long, Department> deptMap = new HashMap<>();
//        allDepartments.forEach(dept->{
//            deptMap.put(dept.getId(),dept);
//        });
        // 在内存中组装数据
        for (Department dept : allDepartments) {
            if (null == dept.getParentId()){
                result.add(dept);
            }else {
                Department parent = deptMap.get(dept.getParentId());

                parent.getChildren().add(dept);
            }
        }
        return result;
    }
}
